/* 
  Title:   Functions for Dashboard
  Author:  www.w3monitor.com 
*/

/* ----------------------------------------------------- */
/* -----                Global Data                ----- */
/* ----------------------------------------------------- */
var url_cp_mon = g_site_root_ajax+"/members/cp__mon.php";
var url_cp_tm = g_site_root_ajax+"/members/cp__tm.php";

var thePointerColor = '#CCFFCC';
var theMarkColor = '#FFCC99';

/* ----------------------------------------------------- */
/* -----       Highlighting rows in dashboard      ----- */
/* ----------------------------------------------------- */
var inCB = false;

function dbrd_row_action(mid, theAction, theDefaultColorId)
{
	var cb = document.getElementById('cbMon_'+mid);
	var row = document.getElementById('idMonRow_'+mid);
	if (!cb || !row) {
        alert('Error - CheckBox or Row with id = '+mid+' not found.');
        return;
    }
    
    if (theAction == 'cb_over') {
        inCB = true;
        return;
    }
    if (theAction == 'cb_out') {
        inCB = false;
        return;
    }

	// show arrow right/down active/inactive depends on 
	// section state and action
	if (theAction == 'over') {
		// show highlighted arrow
		dbrd_set_arrow(mid, !isSection(mid), true);
	}
	if (theAction == 'click') {
		// show highlighted arrow
		dbrd_set_arrow(mid, isSection(mid), true);
	}
	if (theAction == 'out') {
		// show standart arrow
		dbrd_set_arrow(mid, isSection(mid), false);
	}

    if (theAction == 'click' && !inCB) {
        doSection(mid);
        return;
    }

	var theColor = theDefaultColorId;
	
	if (cb.checked) {
		theColor = theMarkColor;
	}
	else {
		if (theAction == 'over') theColor = thePointerColor;
	}
	
    row.style.background = theColor;
}

function dbrd_set_arrow(mid, isOpened, isActive)
{
	var el = document.getElementById('cpMonArr_'+mid);
    if (!el) {
        alert('Error - arrow image with id = '+mid+' not found.');
        return;
    }
	el.src = '../images/arr_'+
		(isOpened ? 'opened' : 'closed')+
		'.gif';
}


/* ----------------------------------------------------- */
/* -----          Open/Close/Load Monitors         ----- */
/* ----------------------------------------------------- */
var isSectionLoaded = new Array();


function getMonitorIDs() {
    var s = document.getElementById('cp_ids').value;
    return s.split(",");
}

function midToIndex(mid) {
    var arr = getMonitorIDs();
    for (i = 0; i < arr.length; ++i)
        if (arr[i] == mid) return i;
    return -1;
}

function setSection(mid, doOpen) {
    var el = document.getElementById('idMonDiv_'+mid);
	if (doOpen) {
		el.style.display="block";
		//el.style.visibility="visible";
		//el.style.position="relative";
        //el.style.top='';
	} else {
		el.style.display="none";
		//el.style.visibility="hidden";
		//el.style.position="absolute";
        //el.style.top='-10000px';
	}	
}

function isSection(mid) {
	//return (document.getElementById('idMonDiv_'+mid).style.visibility != "hidden");
    return (document.getElementById('idMonDiv_'+mid).style.display != "none");
}

function doSection(mid) {
    var ind = midToIndex(mid);
    if (ind < 0) return;
    if (!isSectionLoaded[ind]) 
    {
        dbrdActivityIndicator('idMonDivContent_'+mid, 'load');
        
        // Load section with Ajax
        onLoad =          
        ajaxLoadDataToInnerHtmlExt(
            ajaxAppendToUrl(
    			url_cp_mon,
    			ajaxVarListToUrl(new Array(
    				{n: 'mid', v: mid},
    				{n: 'out', v: 'det'}
    			))),
            'idMonDivContent_'+mid,
            function (task) {
                update_hl_ex(task.userData.mid);
            },
            { 'mid': mid }
        );

        isSectionLoaded[ind] = true;
    }
	setSection(mid, !isSection(mid));
}
function noSection(mid) {
	setSection(mid, false);
}
function invalidateSection(mid) {
    var ind = midToIndex(mid);
    if (ind < 0) return;
    isSectionLoaded[ind] = false;
}

function showAll() {
    var arr = getMonitorIDs();
	for (i = 0; i < arr.length; i++) doSection(arr[i]);
}

function hideAll() {
    var arr = getMonitorIDs();
	for (i = 0; i < arr.length; i++) noSection(arr[i]);
}

function invertAll() {
    var arr = getMonitorIDs();
    if (!arr.length) return;
	if (isSection(arr[0])) hideAll(); else showAll();
}

/* ----------------------------------------------------- */
/* -----       Perform actions in Dashboard        ----- */
/* ----------------------------------------------------- */
function dbrd_clear_cache(actionText) {
    isSectionLoaded = new Array();

    /* TODO: insert HTML here */
	// show spider indicator activity
	var el1 = document.getElementById('div_tm');
	var el2 = document.getElementById('div_tm_action');
	el1.innerHTML = el2.innerHTML;
	var el2text = document.getElementById('tm_action_text');
	el2text.innerHTML = actionText;
}

function dbrdActivityIndicator(divName, action) {
  	var div = document.getElementById(divName);
    if (!div) {
        alert('Element "'+divName+'" not found.');
        return;
    }

    var strClassName = '';
    if (divName == 'divNewMon') strClassName = 'dash-monitor';
    
    var text = "Loading...";
    if (action == "load") text = "Loading...";
    if (action == "save") text = "Saving...";
    
	var s = 
		'<table class='+strClassName+' cellspacing="10" cellpadding="0">'+
		'<tr>'+
		'<td width="39"><img src="../images/throbber.gif" width="39" height="39" alt="" border="0"></td>'+
		'<td><p class="text">'+text+'</td>'+
		'</tr>'+
		'</table>';

	div.innerHTML = s;
}

function on_mt_todo(s) {
    // get selected monitor ids
    var arr = getMonitorIDs();
    var list = new Array();
	for (var i = 0; i < arr.length; i++) {
	    var el = document.getElementById('cbMon_'+arr[i]);
        if (el) {
            if (el && el.checked) {
                list.push( arr[i] );
            }
        }
    }
    
    if (!list.length) {
        alert('Please select at least one monitor.');
        return;
    }

	if (s == "remove") {
		if (!confirm("Are you sure you want to delete selected monitor(s)?")) {
			return;
		}
	}
	
	var action = 'Loading...';
	if (s == 'pause')		action = 'Pausing...';
	if (s == 'activate')	action = 'Resuming...';
	if (s == 'remove')		action = 'Deleting...';
    
    for (var i = 0; i < list.length; i++)
    {
        var mid = list[i];
        var url = ajaxAppendToUrl(
    		url_cp_mon,
            ajaxVarListToUrl(new Array(
                {n: 'maction', v: s},
                {n: 'mid', v: mid},
                {n: 'out', v: 'row'}
            ))
        );

        if (s != 'remove') {
            // Updated monitor and load data
        	ajaxLoadDataToInnerHtml(
                url,
        		'divMonRow_'+mid
        	);
        }
        else {
            // Delete monitor
            ajaxSubmitDataExt(
                url,
                function (task) {
                    // Remove monitor's div from dashboard
          	        var div = document.getElementById('divMon_'+task.userData.mid);
                    div.parentNode.removeChild(div);
                },
                { 'mid': mid }
            );
        }
        invalidateSection(mid);
    }
}

function on_goto_page(pn) {
	ajaxLoadDataToInnerHtml(
		ajaxAppendToUrl(
			url_cp_tm,
			ajaxVarListToUrl(new Array(
				{n: 'curr_page', v: pn.toString()}
			))),
		"div_tm");
    dbrd_clear_cache('Loading...');
}

function on_mt_add(mid_ref) {
    // create 'divNewMon' element if expected
    var div = document.getElementById('divNewMon');
    if (!div) {
        div = document.createElement('div');
        div.id = 'divNewMon';

        var divMonitors = document.getElementById('divMonitors');
        divMonitors.insertBefore(div, divMonitors.firstChild);
    }
    
    dbrdActivityIndicator('divNewMon', 'load');
    
    var params = new Array( {n: 'maction', v: "new"} );
    if (mid_ref != undefined) {
        params.push( {n: 'mid_ref', v: mid_ref} );
    }
    
	ajaxLoadDataToInnerHtml(
		ajaxAppendToUrl(
			url_cp_mon,
			ajaxVarListToUrl( params )
        ),
		"divNewMon"
     );
}

function do_save_monitor(mid, doAddAnother) {
    var form_data = ajaxFormToUrl("form_monitor_"+mid);
    dbrdActivityIndicator('idMonDivContent_'+mid, 'save');
                          
    if (mid > 0) {
    	var onMonitorSaved = function (task) {
            if (task.userData.doAddAnother) {
                on_mt_add(task.userData.mid);
            }
        }
        
    	ajaxLoadDataToInnerHtmlExt(
            ajaxAppendToUrl(
        		url_cp_mon,
                ajaxVarListToUrl(new Array(
				    {n: 'maction', v: 'save'}
			    )),
                form_data
            ),
    		'divMon_'+mid,
            onMonitorSaved,
            { 'mid': mid, 'doAddAnother': doAddAnother }
    	);
        invalidateSection(mid);
    }
    else {
    	onNewMonitorSaved = function (task) {
            // get content of the div for new monitors
            var div = document.getElementById('divNewMon');
            var s = div.innerHTML;

            // get new monitor id
            var mid = getMonitorIdFromResponse(s);
            if (mid <= 0) {
                alert('New Monitor ID not found.');
                return;
            }

            // remove div
            div.parentNode.removeChild(div);
                           
            // copy new monitor div to another div
            var div2 = document.getElementById('divMonitors');
            div2.innerHTML = s + div2.innerHTML;
            
            
            // add id to string of ids
            var s = document.getElementById('cp_ids').value;
            if (s.length) s = ',' + s;
            s = mid + s;
            document.getElementById('cp_ids').value = s;
                                      
            // add place in array
            isSectionLoaded.unshift(false);
                                          
            if (task.userData.doAddAnother) {
                on_mt_add(mid);
            }
    	}
              
    	ajaxLoadDataToInnerHtmlExt(
    		ajaxAppendToUrl(
    			url_cp_mon,
                ajaxVarListToUrl(new Array(
				    {n: 'maction', v: 'save'}
			    )),
    			form_data
    		),
    		'divNewMon',
            onNewMonitorSaved,
            {'doAddAnother': doAddAnother}
    	);
    }
}

function do_cancel_monitor(mid) {
	/*if (!confirm("Are you sure you want to cancel changes?")) {
		return;
	}*/
    
    // reset data in form
    var f = document.getElementsByName('form_monitor_'+mid)[0];
    f.reset();
                         
    // hide section
    noSection(mid);
}

function do_show_advanced(mid) {
	var el = document.getElementById('idMonDivExt_'+mid);
	var el2 = document.getElementById('idEditAdvMonSet_'+mid);
    var isVis = (el.style.visibility == "visible");
    
    var text = "Edit advanced monitor settings ";
    
    if (!isVis) {
    	el.style.visibility="visible";
    	el.style.position="relative";
        el.style.top="";
        el2.value = text + "<";
    }
    else {
    	el.style.visibility="hidden";
    	el.style.position="absolute";
        el.style.top="-10000";
        el2.value = text + ">";
    }
}

function getMonitorIdFromResponse(s) {
    // get id of monitor "... divMon_XXX ..."
    var i = s.indexOf('divMon_');
    if (i < 0) return -1;
    
    i += ('divMon_').length;
    s = s.substring(i);
    
    var mid = parseInt(s);
    if (mid == NaN) return -1;
         
    return mid;
}


///////////////////////////////////////////////////////////////////////////////
// Settings groups //
///////////////////////////////////////////////////////////////////////////////

function ShowSettingGroup(groupid, mid) {
	groupsArr = new Array(1,2,3,4);

	var el = document.getElementById('settings_'+groupid+'_'+mid);
	var elimg = document.getElementById('setimg_'+groupid+'_'+mid);
    var isVis = (el.style.display == "block");
    
    if (!isVis) {
    	el.style.display = "block"
		elimg.src="/images/arrow_up.gif"
    }
    else {
    	el.style.display = "none"
		elimg.src="/images/arrow_down.gif"
    }
}






